# This is the main file

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor

# This is for config files and GPOs
from xml.etree.ElementTree import ElementTree
from xml.etree import ElementTree as ET

import sys

# Fot the log
import traceback

# UGP local imports
from defaults import *

class UGPProtocol(Protocol):
	def dataReceived(self, data):
	
		print "RAW Data received:", data
		# Here we must check for the protocol commands
		filteredData = str(data).replace('\n', '')
		
		print "Filtered Data received:", filteredData
		
		if filteredData == "GET CONFIG VERSION":
			gpo_root = self.factory.gpo_xml.getroot()
			self.transport.write( "GPO VERSION = " + str(gpo_root.get( 'version', 'unkown' ) ))
		elif filteredData == "GET GPO FILE":
			self.sendGPOFile()
		else:
			self.transport.write('Error: Command not recognized')
	
	def sendGPOFile(self):
		# We read the gpo file and then we send it
		root = self.factory.gpo_xml.getroot()
		self.transport.write( '<!--GPO FILE-->\n' + str( ET.tostring(root) ) )


	def connectionMade(self):
		# TODO: Write a log with each connection
		print "Conection made ..."

class UGPFactory(Factory):
	
	# Set the protocol
	protocol = UGPProtocol
	
	def __init__(self, config_xml, gpo_xml):
		# Set the config and gpo
		self.config_xml = config_xml
		self.gpo_xml = gpo_xml


if __name__ == "__main__":

	# Default port conf
	bind = dict()
	config_xml = None
	gpo_xml = None
	
	# Check for parameters
	if len(sys.argv) > 1:
		try:
			# We get the params
			for param in sys.argv:
				if param[0:7] == '--conf=':
					config_file = param[7:len(param)]
		except Exception, ex:
			print ex
			# Finish the execution
			traceback.print_exc(file=sys.stdout)
			sys.exit()
	if config_file:
		# We have passed a config file to the server
		try:
			config_xml = ElementTree()
			config_xml.parse(config_file)
			config = config_xml.getroot()
			for item in list(config):
				if item.tag == 'net':
					# Network conf
					bind = item.find('bind')
				elif item.tag == 'gpo':
					gpo_location = item.find('location')
		except Exception, ex:
			print ex
			traceback.print_exc(file=sys.stdout)
			sys.exit()
	
	gpo_file = gpo_location.get('url', '')
	if gpo_file:
		try:
			# Read the gpo file
			gpo_xml = ElementTree()
			gpo_xml.parse(gpo_file)
		except Exception, ex:
			print ex
			traceback.print_exc(file=sys.stdout)
			sys.exit()
			
	# Create the server, binding to localhost on port
	# server = SocketServer.TCPServer((bind.get('host', default_host), int(bind.get('port', default_port))), MyTCPHandler(gpo_xml, config_xml))
	reactor.listenTCP( int( bind.get('port', default_port) ), UGPFactory( config_xml, gpo_xml ) )

	# Activate the server; this will keep running until you
	# interrupt the program with Ctrl-C
	# server.serve_forever()
	reactor.run()
	
